/*
 * www.unisinsight.com Inc.
 * Copyright (c) 2018 All Rights Reserved
 */
package com.fengwuj.mutils.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
 * 修订记录：
 * jiangbo 2020/1/7 19:11 创建
 *
 * @author jiangbo
 */
@Slf4j
public class POIExcelUtils {
    private static final int PACE_100 = 100;

    private POIExcelUtils() {
    }

    public static void  getOutStreamResponse(SXSSFWorkbook wb, String userCode,String fileName) {
        log.info("开始导出:{},{}",userCode,fileName);
        File file = new File(fileName);
        log.info("文件信息:{}",file.getAbsolutePath());
        if (!file.getParentFile().exists()){
            log.info("创建父文件");
            file.getParentFile().mkdirs();
        }
        log.info("开始导出文件");
        try(FileOutputStream out = new FileOutputStream(fileName)) {
            wb.write(out);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            wb.dispose();
        }
        log.info("导出成功：{}",userCode);
    }

    public static void deleteOutExcel(String realPath) {
        try {
            Files.deleteIfExists(Paths.get(realPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SXSSFWorkbook creatWorkbook(String name){
        ClassPathResource classPathResource=new ClassPathResource(name);
        SXSSFWorkbook workbook;
        try(InputStream in = new BufferedInputStream(classPathResource.getInputStream())) {
            workbook  = new SXSSFWorkbook(new XSSFWorkbook(in),PACE_100);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return workbook;
    }
}
